//
//  KSNetWorkTool.swift
//  ANOA
//
//  Created by 邱仙凯 on 2022/4/18.
//  Copyright © 2025 aowang. All rights reserved.
//

import UIKit
import Alamofire
import SVProgressHUD
import Moya

class KSNetWorkTool: NSObject {
    private override init() {}
     static let shared = KSNetWorkTool()
    /// 检测是否开启联网
    /// 返回一个布尔值,用于实时监测网络状态
       func netIsReachable() -> Bool {
           var res: Bool = false
           let netManager = NetworkReachabilityManager()
           if netManager?.status == .reachable(.ethernetOrWiFi) || netManager?.status == .reachable(.cellular) { res = true }
           return res
       }
    
    func checkService(withCode code: Int, loginVC: UIViewController) -> Bool {
        if code == 502 || code == 503 || code == 504 {
            dealFilure(path: "", error: nil, loginVC: loginVC, errHandle1: nil, errHandle2: nil, errHandle3: nil)
            return false
        }
        
        return true
    }
    
    /// 检查服务更新状态
    /// 在接口超时或无响应时调用
    func checkUpdating(complete: ((String) -> Void)?) {
        var url = "http://tools.zhuok.com.cn:8134/JenkinsTaskController/checkUpdating?c_date=\(Date.nowTimeToSecond)"
        
        var source = ""
        if PlatformManager.shared.platform == .aoWang {
//            source = "1"
        } else if PlatformManager.shared.platform == .zhuYouAn_Old {
            source = "2"
        } else if PlatformManager.shared.platform == .zhuYouAn {
            source = "3"
        }
        
        if source.count > 0 {
            url.append("&c_source=\(source)")
                        
            url = url.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) ?? ""
            
            let Auth_header  = [ "token" : TOKEN ]
            let headers = HTTPHeaders(Auth_header)
            AF.request(url, method: .get, parameters: nil, headers: headers).response { (response) in
               switch response.result {
                   case .success:
                       if let data = response.data {
                           let resultJSON = JSON.init(data)
                           
                           var info = ""
                           if resultJSON["flag"] == "true" {
                               info = "\(resultJSON["message"])"
                           }
                           
                           complete?(info)
                       }
                   case .failure(_):
                       KSToast("网络出错")
                       SVProgressHUD.dismiss()
               }
            }
        } else {
            complete?("")
        }
    }
    
    func dealFilure(path: String, error: MoyaError?, loginVC: UIViewController, errHandle1: ((KSNetworkError) -> Void)?, errHandle2:(() -> Void)?, errHandle3:((String) -> Void)?) {
        if !KSNetWorkTool.shared.netIsReachable() {
            KSToast("请到设置-蜂窝网络-[当前app] 里，开启无线局域网与蜂窝数据权限")
        } else {
            // 检查服务器跟新状态
            KSNetWorkTool.shared.checkUpdating { str in
                if str.count > 0 {
                    if let window = UIApplication.shared.windows.filter({ $0.isKeyWindow }).first {
                        if (window.rootViewController!.isKind(of: loginVC.classForCoder)) == false {
                            // 当前不是在登录页
                            // 去登录页
                            let alert = UIAlertController.init(title: str, message: nil, preferredStyle: .alert)
                            let cancelAction = UIAlertAction.init(title: "取消", style: .destructive)
                            let sureAction = UIAlertAction.init(title: "确定", style: .default) { _ in
                                
                                let animation = {() -> Void in
                                    let oldState = UIView.areAnimationsEnabled
                                    UIView.setAnimationsEnabled(false)
                                    window.rootViewController = loginVC
                                    UIView.setAnimationsEnabled(oldState)
                                }
                                
                                UIView.transition(with: window, duration: 0.8, options: .transitionCrossDissolve, animations: animation, completion: { _ in })
                            }
                            
                            alert.addAction(cancelAction)
                            alert.addAction(sureAction)
                            window.rootViewController?.present(alert, animated: true)
                        } else {
                            KSToast(str)
                        }
                    }
                    

                    errHandle1?(.serviceUpdating)
                    errHandle2?()
                    errHandle3?("数据格式错误")
  
                } else {
                    if let underlyingError = error?.errorDescription {
                        if underlyingError.contains("超时") {
                            KSToast("\(path),请求超时")
                            errHandle1?(.outTime)
                            errHandle2?()
                            errHandle3?("数据格式错误")
                            
                        } else {
                            KSToast("发生错误: \(underlyingError)")
                            errHandle1?(.other)
                            errHandle2?()
                            errHandle3?("")
                        }
                    } else {
                        KSToast("发生错误: \(error.unwrap)")
                        errHandle1?(.other)
                        errHandle2?()
                        errHandle3?("数据格式错误")
                    }
                }
            }
        }
    }
}
